<template>
    <div style="padding-bottom: 30px">
        <div class="mapping-toolbar">
            <span>{{i18n('formula.fieldMapping', '字段映射')}}</span>
            <a-button-group>
                <a-button @click="reloadColumns()" type="primary">
                    {{ i18n('button.selectField', '选择字段') }}
                </a-button>
                <a-button @click="removeRows">
                    {{ $ti18('rxList.delBtn', '删除') }}
                </a-button>
                <a-button @click="upRow">
                    {{ i18n('button.upward', '向上') }}
                </a-button>
                <a-button @click="downRow">
                    {{ i18n('button.downward', '向下') }}
                </a-button>
                <a-button @click="moveTopUp">
                    {{ i18n('button.moveTopUp', '置顶') }}
                </a-button>
                <a-button @click="moveBottomUp">
                    {{ i18n('button.moveBottomUp', '置底') }}
                </a-button>
            </a-button-group>
        </div>

        <div class="mapping-box">

            <div class="mapping-content">
                <rx-grid
                    ref="table"
                    :showPage="false"
                    :dataSource="value.gridData"
                    :columns="dataGridColumn"
                    :multiSelect="true"
                    :allowRowSelect="true"
                    :heightAuto="true"
                >
                    <span slot="fieldName" slot-scope="{text,record}">
                        {{ record.comment }}({{ text }})
                    </span>
                    <span slot="columnType" slot-scope="{text,record}">
                                <span v-html="renderDataType(record)"></span>
                            </span>
                    <span slot="isNull" slot-scope="{text,record}">
                        <a-tag :color="nullMap[text].color">
                            <span>{{ nullMap[text].text }}</span>
                        </a-tag>
                    </span>
                    <span slot="mapType" slot-scope="{text,record,index,blur}">
                        <a-select :options="mapTypes" v-model="record.mapType"
                                  @change="changeMapType($event,record)"
                                  @blur="blur(index,'mapType',text,record)"
                                  style="width: 100%"
                                  :dropdown-menu-style="{width:'300px'}"
                                  :dropdownMatchSelectWidth="false"
                        ></a-select>
                    </span>
                    <span slot="mapValue" slot-scope="{text,record,index,blur}">
                    <a-select v-if="record.mapType=='field' " :options="fieldDatas"
                              v-model="record.mapValue"
                              @blur="blur(index,'mapValue',text,record)"
                              style="width: 100%"
                              :dropdown-menu-style="{width:'300px'}"
                              :dropdownMatchSelectWidth="false"
                    ></a-select>
                    <a-select v-if="record.mapType=='contextMap' "
                              :options="contextMap"
                              v-model="record.mapValue"
                              @blur="blur(index,'mapValue',text,record)"
                              style="width: 100%"
                              :dropdown-menu-style="{width:'300px'}"
                              :dropdownMatchSelectWidth="false"
                    ></a-select>
                    <a-select v-if="record.mapType=='mainField' " :options="mainFieldDatas"
                              v-model="record.mapValue"
                              @blur="blur(index,'mapValue',text,record)"
                              :dropdown-menu-style="{width:'300px'}"
                              style="width: 100%"
                              :dropdownMatchSelectWidth="false"
                    ></a-select>
                    <a-input v-if="record.mapType=='fixValue'"
                             v-model="record.mapValue"
                             @blur="blur(index,'mapValue',text,record)"/>
                    <rx-input-button
                        v-if="record.mapType=='scriptValue' "
                        @click="openScript($event,blur,index,record)"
                        v-model="record.mapValue"></rx-input-button>
                    <rx-input-button
                        v-if="record.mapType=='seqValue' "
                        @click="openSeqId($event,blur,index,record)"
                        v-model="record.mapValue"></rx-input-button>
                </span>
                </rx-grid>
            </div>
        </div>
    </div>

</template>

<script>
/**
 * @Author : yangsanjin
 * @Date: 2024-09-13 14:24
 */
import FormDbApi from "@/api/form/bo/formDb";
import reloadFormulaPaneColumnDialog from "@/views/modules/form/core/listLayout/reloadFormulaPaneColumnDialog";

import {Dialog, Util,RxGrid} from "@lowcode/jpaas-common-lib"
import FormTableFormulaScript from "@/views/modules/form/core/TableForrmula/FormTableFormulaScript";
import formBoControls from "@/api/form/bo/formBoControls";
import FormBoEntityApi from "@/api/form/bo/formBoEntity"

export default {
    name: "FormulaFieldMapping",
    mixins: [formBoControls],
    components:{
        RxGrid
    },
    props:{
        value: {}
    },
    data(){
        return {

            dataGridColumn: [
                {
                    title: this.i18n('formula.serial', '序号'),
                    type: 'indexColumn',
                    width: 40,
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'}
                },
                {
                    title: this.i18n('list.field', '字段'),
                    dataIndex: 'fieldName',
                    width: 100,
                    scopedSlots: {customRender: 'fieldName'}
                },
                {
                    title: this.i18n('list.dataType', '数据类型'),
                    dataIndex: 'columnType',
                    width: 80,
                    scopedSlots: {customRender: 'columnType'}
                },
                {
                    title: this.i18n('list.nullable', '可空'),
                    dataIndex: 'isNull',
                    width: 40,
                    scopedSlots: {customRender: 'isNull'}
                },
                {
                    title: this.i18n('list.valueSource', '值来源'),
                    dataIndex: 'mapType',
                    displayField: 'mapTypeName',
                    allowCellEdit: true,
                    width: 100,
                    scopedSlots: {customRender: 'mapType'}
                },
                {
                    title: this.i18n('list.value', '值'),
                    dataIndex: 'mapValue',
                    allowCellEdit: true,
                    width: 100,
                    scopedSlots: {customRender: 'mapValue'}
                }
            ],
            nullMap: {
                true: {color: 'green', text: this.i18n('isTestMap.yes', '是')},
                false: {color: 'red', text: this.i18n('isTestMap.no', '否')}
            },
            mapTypes: [{value: 'none', label: this.i18n('isMapTypes.none', '无')},
                {value: 'field', label: this.i18n('isMapTypes.getFromField', '字段')},
                {value: 'null', label: this.i18n('isMapTypes.setToNull', '设置为空')},
                {value: 'mainField', label: this.i18n('isMapTypes.mainField', '主表字段')},
                {value: 'fixValue', label: this.i18n('isMapTypes.fixValue', '固定值')},
                {value: 'scriptValue', label: this.i18n('isMapTypes.scriptValue', '脚本计算')},
                {value: 'srcPkId', label: this.i18n('isMapTypes.srcPkId', '源表主键字段值')},
                {value: 'pkId', label: this.i18n('isMapTypes.pkId', '由系统产生的主键字段值')},
                {value: 'mainPkId', label: this.i18n('isMapTypes.mainPkId', '源主表主键字段值')},
                {value: 'mainPk', label: this.i18n('isMapTypes.mainPk', '主表主键字段值(新建表单时使用)')},
                {value: 'seqValue', label: this.i18n('isMapTypes.seqValue', '流水号')},
                {value: 'batId', label: this.i18n('isMapTypes.batValue', '批次ID')},
                {value: 'contextMap', label: this.i18n('isMapTypes.contextApi', '上下文')},
            ],
            contextMap: [
                {value: 'curDate', label: this.i18n('isMapTypes.curDate', '当前时间')},
                {value: 'curUserId', label: this.i18n('isMapTypes.curUserId', '当前用户Id')},
                {value: 'curUserName', label: this.i18n('isMapTypes.curUserName', '当前用户姓名')},
                {value: 'curDepId', label: this.i18n('isMapTypes.curDepId', '当前部门Id')},
                {value: 'curDepName', label: this.i18n('isMapTypes.curDepName', '当前部门名称')},
                {value: 'curInstId', label: this.i18n('isMapTypes.curInstId', '当前机构Id')},
                {value: 'curCompanyId', label: this.i18n('isMapTypes.curCompanyId', '当前公司ID')},
                {value: 'bpmInstId', label: this.i18n('isMapTypes.bpmInstId', '流程实例ID')}
            ],
            fieldDatas: [],
            mainFieldDatas: [],

        }
    },
    computed: {
        table() {
            return this.$refs.table;
        },
    },
    created(){
        this.loadData();
        let boDefId=this.value.boDefId;
        let boName=this.value.boName;
        this.loadBoAttrs("mainFieldDatas", boDefId, "_main",  true);
        this.loadBoAttrs("fieldDatas", boDefId, boName, true);
    },
    methods:{
        i18n(name, text, key) {
            return this.$ti18(name, text, "formTableFormula", key);
        },
        parseFields(list) {
            for (let i = 0; i < list.length; i++) {
                list[i].mapType = '';
                list[i].mapValue = '';
            }
            return list;
        },
        renderDataType(record) {
          var val = record.columnType;
          if (val == "varchar") {
            return val + "(" + record.charLen + ")";
          } else if (val == "number") {
            if (record.decimalLen == 0) {
              return val + "(" + record.intLen + ")";
            } else {
              return val + "(" + record.intLen + "," + record.decimalLen + ")"
            }
          }
          return val;
        },
        loadData() {
            if (!this.value.gridData || this.value.gridData.length == 0) {
                FormDbApi.getByName("dsName=" + this.value.dsName + "&tbName=" + this.value.tableName).then(data => {
                    let list = data.columnList;
                    this.value.gridData = this.parseFields(list);
                })
            }

        },
        loadBoAttrs(comboxId, boDefId, entName,  showName) {
            var self = this;
            FormBoEntityApi.getFieldByBoDefId(boDefId, entName).then(data => {
                data = data.map(item => {
                    return {label: item.comment, value: item.name, isSingle: item.isSingle, control: item.control}
                })
                if (!showName) {
                    self[comboxId] = data;
                } else {
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        if(item.control=='rx-address'){
                            var addressAry=[
                                {value:item.value+"-province",label:item.label+"(" + this.$comi18('listDef.province', '省') + ")" },
                                {value:item.value+"-province_code",label:item.label+"(" + this.$comi18('listDef.province', '省') + "Code)" },
                                {value:item.value+"-city",label:item.label+"(" + this.$comi18('listDef.city', '市') + ")"},
                                {value:item.value+"-city_code",label:item.label+"(" + this.$comi18('listDef.city', '市') + "Code)"},
                                {value:item.value+"-county",label:item.label+"(" + this.$comi18('listDef.county', '县(区)') + ")"},
                                {value:item.value+"-county_code",label:item.label+"(" + this.$comi18('listDef.county', '县(区)') + ")Code)"},
                                {value:item.value+"-address",label:item.label+"(" + this.$comi18('listDef.detailtAddress', '详细地址') + ")"},
                            ];
                            self[comboxId].push(...addressAry);
                            continue;
                        }
                        if (item.isSingle == 0) {
                            var singleAry=[
                                {value:item.value+"-value",label:item.label},
                                {value:item.value+"-label",label:item.label+"(" + this.i18n('form.name', '名称') + ")"},
                            ];
                            self[comboxId].push(...singleAry);
                            continue;
                        }
                        self[comboxId].push(item);
                    }
                }

            })
        },

        /**
         * 修改字段映射类型。
         * @param val
         * @param record
         */
        changeMapType(val, record) {
            let ary = this.mapTypes.filter(item => {
                return item.value == val;
            });
            if (ary && ary.length > 0) {
                record.mapTypeName = ary[0].label;
            }
        },
        openSeqId(vm, blur, index, record) {
            Dialog.openSysSeqIdDialog({
                curVm: this, widthHeight: ['1300px', '600px']
            }, function (self, data) {
                vm.setVal(data.alias, data.name);
                record.mapValue = data.alias;
                blur(index, 'mapValue', data.alias, record)
            })
        },
        openScript(vm, blur, index, record) {
            let self = this;
            let source = Util.deepClone(self.value);
            source.condition = record.mapValue;
            let baseConf = {
                "curVm": self,
                component: FormTableFormulaScript,
                title: self.i18n('form.scriptTitle', '设置字段脚本'),
                widthHeight: ['1000px', '650px'],
                data: {
                    source: source
                }
            };
            Util.open(baseConf, function (action, data) {
                if (action === 'ok') {
                    record.mapValue = data;
                }
                blur(index, 'mapValue', data, record)
            });
        },
        addField(data) {
            data=Util.deepClone(data);
            let self_ = this;
            let fieldMap = this.toMap(this.value.gridData, "fieldName");
            let appendFields = [];
            let tmpFields = self_.parseFields(data);
            //增加字段
            for (let i = 0; i < tmpFields.length; i++) {
                let field = tmpFields[i];
                if (!fieldMap[field.fieldName]) {
                    appendFields.push(field);
                }
            }
            self_.value.gridData.push(...appendFields);
        },
        toMap(rows, keyField) {
            let fieldMap = {};
            for (let i = 0; i < rows.length; i++) {
                let obj = rows[i];
                let key = obj[keyField];
                fieldMap[key] = obj;
            }
            return fieldMap;
        },
        reloadColumns() {
            let self_ = this;
            let tableName = this.value.tableName;
            FormDbApi.getByName("dsName=" + this.value.dsName + "&tbName=" + tableName).then(data => {
                let list = data.columnList;
                let conf = {
                    component: reloadFormulaPaneColumnDialog,
                    title: '重新加载表头',
                    curVm: this,
                    data: {
                        mappingFields: this.mappingFields,
                        reloadFields: list
                    },
                    widthHeight: ['800px', '600px']
                };
                Util.open(conf, function (action, data) {
                    if (action != 'ok') {
                        return;
                    }
                    self_.addField(data);
                });
            })
        },
        removeRows() {
            this.table.removeRows();
        },
        upRow() {
            this.table.moveUp();
        },
        downRow() {
            this.table.moveDown();
        },
        getData(){
            return this.value.gridData;
        },
        moveTopUp(){
            this.table.moveTopUp();
        },
        moveBottomUp(){
            this.table.moveBottomUp();
        },
    }
}
</script>

<style scoped>
.mapping-box{
    width: 100%;
    height: 100%;
    display: grid;
    grid-template-rows: auto 1fr;
}
.mapping-toolbar{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 8px 8px 8px ;
}
</style>